package com.freedom.rpc.thrift.registry;

import java.util.concurrent.atomic.AtomicLong;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.rpc.thrift.common.utils.LoggerUtils;
import com.freedom.rpc.thrift.common.utils.TimeUtils;
import com.freedom.rpc.thrift.server.utils.MyServerProperties;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class MyPublishRunnable implements Runnable {// 基于redis做心跳保活，每3秒钟发送一次publish消息

	private static final Logger logger = LogManager.getLogger(MyPublishRunnable.class);
	private String address = null;
	private long index = 0;
	private static AtomicLong indexer = new AtomicLong(0);

	public MyPublishRunnable(String addr) {
		address = addr;
		index = indexer.getAndIncrement();
	}

	@Override
	public void run() {

		LoggerUtils.info(logger, "heart beat runnable is running...");
		TimeUtils.sleepSeconds(3);// 这里是为了让Thrift server.serve方法执行完毕
		MyServerProperties property = MyServerProperties.getInstance();
		String ip = property.getIp();// 本地监听IP
		int port = property.getPort();// 本地监听port
		//
		while (true) {
			//
			// 先上报心跳publish,尽最大努力!!!，主动心跳
			JedisPoolManager manager = JedisPoolManager.getInstance();
			// 根据地址找到对应的连接池
			JedisPool pool = manager.getJedisPools(address);
			// 0)保证pool不为null
			if (null == pool) {
				TimeUtils.sleepSeconds(1);
				continue;
			}
			//
			// 1)保证jedis不为null
			Jedis jedis = null;
			try {
				jedis = pool.getResource();
			} catch (Exception e) {
				LoggerUtils.error(logger, e.toString());
			}
			if (null == jedis) {
				continue;
			}
			//
			// 2)用jedis执行操作
			boolean error = false;
			try {
				jedis.publish(MyServerProperties.getInstance().getGlobalService(), ip + ":" + port);
				LoggerUtils.debug(logger, "thread [publish-" + index + "] succeed to publish "
						+ MyServerProperties.getInstance().getGlobalService() + "-" + ip + ":" + port);
			} catch (Exception e) {
				LoggerUtils.error(logger, e.toString());
				error = true;
			} finally {
				if (error) {
					pool.returnBrokenResource(jedis);
				} else {
					pool.returnResource(jedis);
				}
			}
			//
			// 睡眠1秒->继续发送主动心跳heartbeat
			TimeUtils.sleepSeconds(1);
			// 结束
		} // while结束

	}// run结束

}// 类定义结束
